<?php
namespace App\GraphQL\Mutations\Device;

use App\Models\Device;
use GraphQL\Type\Definition\ResolveInfo;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use App\Models\FactoryDevice;
use App\Models\GlobalStatistical;
use Illuminate\Support\Facades\DB;

class Add
{

    /**
     * Return a value for the field.
     *
     * @param null $rootValue
     *            Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param mixed[] $args
     *            The arguments that were passed into the field.
     * @param \Nuwave\Lighthouse\Support\Contracts\GraphQLContext $context
     *            Arbitrary data that is shared between all fields of a single query.
     * @param \GraphQL\Type\Definition\ResolveInfo $resolveInfo
     *            Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $input = $args['input'];
            $factoryDevice = $this->validate($input['factory_device_id']);
            $data = [
                'user_id'=>$factoryDevice->user_id,
                'status'=>'DORMANT',
                'mac_address'=>$factoryDevice->mac_address,
                'unique_id'=>$factoryDevice->unique_id,
                'connection_password'=>$factoryDevice->connection_password,
            ];
            Device::create($data);
            $factoryDevice->status = 'READONLY';
            $factoryDevice->save();
            $globalStatistical = GlobalStatistical::where('device_count','>',0)->firstOrCreate([]);
            $globalStatistical->increment('device_count');
        });
        return [
            'status' => '200',
            'message' => '入库成功'
        ];
    }

    public function validate($id)
    {
        $old = FactoryDevice::find($id);
        if (! $old) {
            throw new \Exception('厂家设备不存在!');
        }
        if ($old->status === 'READONLY') {
            throw new \Exception('设备已经出厂无法添加!');
        }
        return $old;
    }
}
